package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysPartService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysRoleInfoFunctionService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysRoleInfoFunctionWebService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysRoleService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetAllPartVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Component
public class PartBu {
    @Autowired
    private ISysPartService sysPartService;
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ISysRoleInfoFunctionService sysRoleInfoFunctionService;
    @Autowired
    private ISysRoleInfoFunctionWebService sysRoleInfoFunctionWebService;

    //拿到所有组织
    public SzResult getAllPart(Integer page,Integer pageSize,String partName ,String token,String plantId) throws Exception {
        ArrayList<GetAllPartVo> getAllPartVos = new ArrayList<>();
        if (page!=null && pageSize!=null) {
            Page<SysPart> sysPartPage = new Page<>(page, pageSize);
            QueryWrapper<SysPart> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(partName != null && !partName.equals(""), "PART_NAME", partName);
            queryWrapper.eq("DATA_FROM", plantId);
//            List<SysPart> list = sysPartService.list(queryWrapper);
            IPage<SysPart> page1 = sysPartService.page(sysPartPage, queryWrapper);
            List<SysPart> list = page1.getRecords();
            for (SysPart sysPart : list) {
                GetAllPartVo getAllPartVo = new GetAllPartVo();
                getAllPartVo.setId(sysPart.getId());
                getAllPartVo.setPartName(sysPart.getPartName());
                getAllPartVo.setPartRole(sysPart.getPartRole());
                getAllPartVo.setRoleName(sysRoleService.getById(sysPart.getPartRole()).getRoleName());
                String defaultCodeApp = sysPart.getDefaultCodeApp();
                if (sysPart.getDefaultCodeApp() != null && !sysPart.getDefaultCodeApp().equals("")) {
                    char[] arr = defaultCodeApp.toCharArray();
                    List<String> list1 = new ArrayList<>();
                    for (int i = 0; i < arr.length; i++) {
                        String str = String.valueOf(arr[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunction> queryWrapper1 = new QueryWrapper<>();
                            queryWrapper1.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunction one = sysRoleInfoFunctionService.getOne(queryWrapper1);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list1.add(webFunctionExplain);
                        }
                        getAllPartVo.setAppNameList(list1);
                    }
                } else {
                    getAllPartVo.setAppNameList(null);
                }
                if (sysPart.getDefaultCodeWeb() != null && !sysPart.getDefaultCodeWeb().equals("")) {
                    String defaultCodeWeb = sysPart.getDefaultCodeWeb();
                    char[] arr1 = defaultCodeWeb.toCharArray();
                    List<String> list2 = new ArrayList<>();
                    for (int i = 0; i < arr1.length; i++) {
                        String str = String.valueOf(arr1[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper2 = new QueryWrapper<>();
                            queryWrapper2.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunctionWeb one = sysRoleInfoFunctionWebService.getOne(queryWrapper2);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list2.add(webFunctionExplain);
                        }
                        getAllPartVo.setWebNameList(list2);
                    }
                    getAllPartVos.add(getAllPartVo);
                } else {
                    getAllPartVos.add(getAllPartVo);
                }
            }
            Map<String, Object> map = new HashMap();
            map.put("list", getAllPartVos);
            map.put("total", page1.getTotal());
            return SzResult.success(map);
        }else {
            QueryWrapper<SysPart> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(partName != null && !partName.equals(""), "PART_NAME", partName);
            queryWrapper.eq("DATA_FROM", plantId);
            List<SysPart> list = sysPartService.list(queryWrapper);
            for (SysPart sysPart : list) {
                GetAllPartVo getAllPartVo = new GetAllPartVo();
                getAllPartVo.setId(sysPart.getId());
                getAllPartVo.setPartName(sysPart.getPartName());
                getAllPartVo.setPartRole(sysPart.getPartRole());
                getAllPartVo.setRoleName(sysRoleService.getById(sysPart.getPartRole()).getRoleName());
                String defaultCodeApp = sysPart.getDefaultCodeApp();
                if (sysPart.getDefaultCodeApp() != null && !sysPart.getDefaultCodeApp().equals("")) {
                    char[] arr = defaultCodeApp.toCharArray();
                    List<String> list1 = new ArrayList<>();
                    for (int i = 0; i < arr.length; i++) {
                        String str = String.valueOf(arr[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunction> queryWrapper1 = new QueryWrapper<>();
                            queryWrapper1.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunction one = sysRoleInfoFunctionService.getOne(queryWrapper1);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list1.add(webFunctionExplain);
                        }
                        getAllPartVo.setAppNameList(list1);
                    }
                } else {
                    getAllPartVo.setAppNameList(null);
                }
                if (sysPart.getDefaultCodeWeb() != null && !sysPart.getDefaultCodeWeb().equals("")) {
                    String defaultCodeWeb = sysPart.getDefaultCodeWeb();
                    char[] arr1 = defaultCodeWeb.toCharArray();
                    List<String> list2 = new ArrayList<>();
                    for (int i = 0; i < arr1.length; i++) {
                        String str = String.valueOf(arr1[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper2 = new QueryWrapper<>();
                            queryWrapper2.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunctionWeb one = sysRoleInfoFunctionWebService.getOne(queryWrapper2);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list2.add(webFunctionExplain);
                        }
                        getAllPartVo.setWebNameList(list2);
                    }
                    getAllPartVos.add(getAllPartVo);
                } else {
                    getAllPartVos.add(getAllPartVo);
                }
            }
            Map<String, Object> map = new HashMap();
            map.put("list", getAllPartVos);
            map.put("total", getAllPartVos.size());
            return SzResult.success(map);
        }
    }

    //添加组织
    @Transactional
    public SzResult addPart(String partName, String roleName, String token,String plantId) throws Exception {
        QueryWrapper<SysPart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PART_NAME", partName);
        List<SysPart> list = sysPartService.list(queryWrapper);
        if (list.size() > 0) {
            return SzResult.Error("角色名称已存在");
        }
        SysPart sysPart = new SysPart();
        StringBuilder logMsg = new StringBuilder();
        if (partName != null && !partName.equals("")) {
            sysPart.setPartName(partName);
            logMsg.append("角色名称为：" + partName);
        }
        String DefaultCodeApp = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" +
                "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
        String DefaultCodeWeb = "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
        sysPart.setDefaultCodeApp(DefaultCodeApp);
        sysPart.setDefaultCodeWeb(DefaultCodeWeb);
        if (roleName != null && !roleName.equals("")) {
            sysPart.setPartRole(roleName);
            QueryWrapper<SysRole> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("ID", roleName);
            SysRole sysRole = sysRoleService.getOne(queryWrapper1);
            logMsg.append("组织角色为：" + sysRole.getRoleName());
        }
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        sysPart.setDataFrom(plantId);
        sysPartService.save(sysPart);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("新增角色信息", user1.getTrueName(), "新增了" + partName + "的角色信息,新增内容为:" + logMsg,plantId);
        return SzResult.Success();
    }

    //添加组织默认权限码Web
    public SzResult getDefaultCodeWeb(List list, String id, String token,String plantId) throws Exception {
        String DefaultCodeWeb = "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
        //将DefaultCodeWeb转换为集合
        Integer[] list1 = new Integer[DefaultCodeWeb.length()];
        for (int i = 0; i < DefaultCodeWeb.length(); i++) {
            list1[i] = Integer.parseInt(DefaultCodeWeb.substring(i, i + 1));
        }
        for (int i = 0; i < list.size(); i++) {
            //将list集合中的值转换为int类型
            int a = Integer.parseInt(list.get(i).toString());
            //将list集合中的值赋值给DefaultCodeWeb
            list1[a] = 1;
        }
        //将list1集合转换为字符串
        String defaultCodeWeb = Arrays.toString(list1).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");

        //根据id获取组织信息
        SysPart sysPart = sysPartService.getById(id);
        sysPart.setDefaultCodeWeb(defaultCodeWeb);
        sysPartService.updateById(sysPart);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("添加角色默认权限码web", user1.getTrueName(), "添加了" + sysPart.getPartName() + "角色的" + DefaultCodeWeb + "权限码",plantId);
        return SzResult.Success();
    }

    //添加组织默认权限码App
    public SzResult getDefaultCodeApp(List list, String id, String token,String plantId) throws Exception {
        String DefaultCodeApp = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" +
                "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
        //将DefaultCodeApp转换为集合
        Integer[] list1 = new Integer[DefaultCodeApp.length()];
        for (int i = 0; i < DefaultCodeApp.length(); i++) {
            list1[i] = Integer.parseInt(DefaultCodeApp.substring(i, i + 1));
        }
        for (int i = 0; i < list.size(); i++) {
            //将list集合中的值转换为int类型
            int a = Integer.parseInt(list.get(i).toString());
            //将list集合中的值赋值给DefaultCodeWeb
            list1[a] = 1;
        }
        //将list1集合转换为字符串
        String defaultCodeApp = Arrays.toString(list1).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");

        //根据id获取部

        // 门信息
        SysPart sysPart = sysPartService.getById(id);
        sysPart.setDefaultCodeApp(defaultCodeApp);
        sysPartService.updateById(sysPart);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("添加角色默认权限码app", user1.getTrueName(), "添加了" + sysPart.getPartName() + "角色的" + DefaultCodeApp + "权限码",plantId);
        return SzResult.Success();
    }

    //修改组织信息
    public SzResult updatePart(String id, String partName, String partRole, String token,String plantId) throws Exception {
        SysPart sysPart = sysPartService.getById(id);
        StringBuilder logMsg = new StringBuilder();
        if (sysPart == null) {
            return SzResult.Error("组织不存在");
        }
        String partName1 = sysPart.getPartName();
        if (partName == null || partName.isEmpty()) {
            return SzResult.Error("角色名称不能为空");
        }
        if (partRole == null || partRole.isEmpty()) {
            return SzResult.Error("角色等级不能为空");
        }
//        判断更新了什么
        if (partName1.equals(partName) && sysPart.getPartRole().equals(partRole)) {
            return SzResult.Error("未修改任何信息");
        }
        if (!sysPart.getPartRole().equals(partRole)) {
            sysPart.setPartRole(partRole);
            logMsg.append("角色等级由").append(sysPart.getPartRole()).append("改为").append(partRole).append(";");
        }
        if (!partName1.equals(partName)) {
            sysPart.setPartName(partName);
            logMsg.append("角色名称由").append(partName1).append("改为").append(partName).append(";");
        }
        sysPartService.updateById(sysPart);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("角色信息", user1.getTrueName(), "修改了" + partName1 + "的组织信息,修改内容为:" + logMsg,plantId);
        return SzResult.Success();
    }

    //删除组织
    public SzResult deletePart(String id, String token,String plantId) throws Exception {
        sysPartService.removeById(id);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("删除组织信息", user1.getTrueName(), "删除了" + sysPartService.getById(id) + "的组织信息",plantId);
        return SzResult.Success();
    }

//    updateDefaultCodeWeb
    public  SzResult updateDefaultCodeWeb (Integer nubmer,String id,Integer ifOn,String token,String plantId) throws Exception {
        QueryWrapper<SysPart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID",id);
        queryWrapper.eq("DATA_FROM",plantId);
        SysPart part = sysPartService.getOne(queryWrapper);
        String defaultCodeWeb = part.getDefaultCodeWeb();
//    defaultCodeWeb转成Integer数组
        Integer[] list1 = defaultCodeWeb.chars()
                .mapToObj(c -> Integer.parseInt(String.valueOf((char) c)))
                .toArray(Integer[]::new);
        list1[nubmer] = ifOn;
        String defaultCodeWeb1 = Arrays.toString(list1).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
        part.setDefaultCodeWeb(defaultCodeWeb1);
        sysPartService.updateById(part);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("WEB_FUNCTION_NUMBER",nubmer);
        SysRoleInfoFunctionWeb sysRoleInfoFunctionWeb = sysRoleInfoFunctionWebService.getOne(queryWrapper1);
        if (ifOn == 0){
            sysLogBu.logRecord("修改组织web默认权限码", user1.getTrueName(), "关闭了" + part.getPartName() + "组织的" + sysRoleInfoFunctionWeb.getWebFunctionExplain() + "权限",plantId);
            return SzResult.success("关闭成功");
        }else {
            sysLogBu.logRecord("修改组织web默认权限码", user1.getTrueName(), "开启了" + part.getPartName() + "组织的" + sysRoleInfoFunctionWeb.getWebFunctionExplain() + "权限",plantId);
            return SzResult.success("开启成功");
        }
    }
//    updateDefaultCodeApp
    public  SzResult updateDefaultCodeApp (Integer nubmer,String id,Integer ifOn,String token,String plantId) throws Exception {
        QueryWrapper<SysPart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("DATA_FROM", plantId);
        SysPart part = sysPartService.getOne(queryWrapper);
        String defaultCodeApp = part.getDefaultCodeApp();
//    defaultCodeApp 转换成数组
        Integer[] list1 = defaultCodeApp.chars()
                .mapToObj(c -> Integer.parseInt(String.valueOf((char) c)))
                .toArray(Integer[]::new);
        list1[nubmer] = ifOn;
        String defaultCodeApp1 = Arrays.toString(list1).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
        part.setDefaultCodeApp(defaultCodeApp1);
        sysPartService.updateById(part);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<SysRoleInfoFunction> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("WEB_FUNCTION_NUMBER", nubmer);
        SysRoleInfoFunction sysRoleInfoFunctionApp = sysRoleInfoFunctionService.getOne(queryWrapper1);
        if (ifOn == 0) {
            sysLogBu.logRecord("修改组织app默认权限码", user1.getTrueName(), "关闭了" + part.getPartName() + "组织的" + sysRoleInfoFunctionApp.getWebFunctionExplain() + "权限",plantId);
            return SzResult.success("关闭成功");
        } else {
            sysLogBu.logRecord("修改组织app默认权限码", user1.getTrueName(), "开启了" + part.getPartName() + "组织的" + sysRoleInfoFunctionApp.getWebFunctionExplain() + "权限",plantId);
            return SzResult.success("开启成功");
        }
    }
}
